<?php
/**
 * File: helper.php.
 * User: Yan<me@xiaoyan.me>
 * DateTime: 2017-12-19 20:46
 */
function getRequestUri()
{

    //# 解决通用问题
    $requestUri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['REQUEST_URI']);
    if(strpos($requestUri,'?') > -1){
        $requestUri = substr($requestUri,0,strpos($requestUri,'?'));
    }
    $requestUri = strlen($requestUri) == 0 ? '/' : $requestUri;
    return strtolower($requestUri);
}

function getFullUrl($uri = null)
{
    return SITE_URL . ($uri ? $uri : getRequestUri());
}
function getResourceUrl($uri = '')
{
    return SITE_URL .$uri;
}

/**
 * @return \App\Core\Router
 */
function router()
{
    return \App\Core\Router::Instance();
}

function jump($url)
{
    if(isAjax()){
        ajaxError('jump to ...',$url,302);
    }
    exit(sprintf('<script>setTimeout(function(){location.href = "%s";},50)</script>', $url));
}
function getClientIP()
{
    $ip = "un_know";

    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
function isAjax()
    {
        if ((isset($_GET['_request']) && $_GET['_request'] == 'ajax')
            || (isset($_GET['request.method']) && $_GET['request.method'] == 'ajax')
        ) {
            return true;
        }
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
            && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
        ) {
            return true;
        }
        return false;
    }
function view($name)
{
    return dirname(__DIR__) . '/res/views/' . $name . '.php';
}

function ajaxSuccess($data = null)
{
    exit(jsonData([
        'code' => 0, 'message' => 'success', 'data' => $data
    ]));
}

function ajaxError($message = 'error', $data = null,$code = 1)
{
    exit(jsonData([
        'code' => $code, 'message' => $message, 'data' => $data
    ]));
}

function jsonData($data)
{
    return json_encode($data, JSON_UNESCAPED_UNICODE);
}